package com.hospital.diagnosis.module.schedule;

import com.hospital.common.pojo.TChatSession;
import com.hospital.diagnosis.module.service.ChatService;
import com.hospital.diagnosis.module.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.hospital.common.enums.diagnosis.module.SessionStatus.*;

/**
 *  定时任务
 */
@Component
public class ScheduleTask
{
    @Autowired
    private ChatService chatService;
    @Autowired
    private RedisUtils redisUtils;
    /**
     *  定时任务：结束超时会话，会话内容归档
     *  每10分钟执行一次
     */
    @Scheduled(fixedRate = 1000 * 60 * 10)
    public void chatSchedule()
    {
        List<TChatSession> chatSessions = chatService.getChats();
        chatSessions.stream()
                .filter(chatSession -> Objects.equals(chatSession.getSessionStatus(), IN_PROGRESS.value) &&
                        chatSession.getCreateTime().plusHours(24).isBefore(LocalDateTime.now()))
                .forEach(chatSession -> {
                    chatSession.setSessionStatus(COMPLETED.value);//修改会话状态为已结束
                    chatService.archiveChat(chatSession);//归档会话
                });
        chatSessions.stream()
                .filter(chatSession -> Objects.equals(chatSession.getSessionStatus(),NOT_PAY.value) &&
                        chatSession.getCreateTime().plusMinutes(30).isBefore(LocalDateTime.now()))
                .forEach(chatSession -> {
                    //chatService.archiveChat(chatSession);//归档未支付会话
                    redisUtils.hDel("chat",chatSession.getSessionId());//在redis中删除未支付会话
                });
    }
}
